<template>
  <div class="lx_addhome">
    <div>
      <van-nav-bar title="发布房源" left-text="返回" left-arrow @click-left="onClickLeft" />
    </div>
    <div style="margin-top: 40px">
      <p><van-field v-model="text" label="标题" /></p>
      <p><van-field v-model="address" label="地址" /></p>
      <p><van-field v-model="price" label="租金" /></p>
      <p>
        <van-field v-model="result" is-link readonly name="area" label="地区选择" placeholder="点击选择省市区"
          @click="showArea = true" />
        <van-popup v-model:show="showArea" position="bottom">
          <van-area :area-list="areaList" @confirm="onConfirm" @cancel="showArea = false" />
        </van-popup>
      </p>
      <p><van-field v-model="houseType" label="租房类型" /></p>
      <p><van-field v-model="desc" label="补充说明" /></p>
      <p><van-field label="上传图片" /></p>
      <van-uploader v-model="fileList" :after-read="afterRead" />
    </div>
    <div class="add">
      <button class="btn" @click="addhouse">发布房源</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
// 定义内容

const text = ref('') //房源名称
const address = ref('') //房源地址
const price = ref('') //房源价格
const desc = ref('') //房源描述
const houseType = ref('') //房源类型
// 房东id
const id = JSON.parse(localStorage.getItem('user') as string)._id
const onClickLeft = () => history.back()
import { areaList } from '@vant/area-data'
import axios from 'axios';
import { ElMessage } from 'element-plus'
const result = ref('')
const showArea = ref(false)
const onConfirm = ({ selectedOptions }) => {
  showArea.value = false
  result.value = selectedOptions.map((item) => item.text).join('/')
}
const fileList = ref([]);


const afterRead = async (file: any) => {
  file.status = 'uploading';
  file.message = '上传中...';
  const formData = new FormData();
  console.log(file.file);
  formData.append('file', file.file);
  console.log(formData);

  try {
    const response = await axios.post('http://localhost:3000/yg/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    if (response.data.code === 200) {
      const data = response.data.path;
      file.status = 'done';
      file.message = '上传成功';
      file.url = data.path;  // 使用后端返回的文件路径
    } else {
      file.status = 'failed';
      file.message = '上传失败';
    }
  } catch (error) {
    console.error('上传错误:', error);
    file.status = 'failed';
    file.message = '上传失败';
  }
};

// 将 fileList 中所有图片的 url 提取成一个数组
/* const imgUrls = fileList.value.map(file => file.objectUrl);
console.log(imgUrls); */
let addhouse = async () => {
  const imgUrls = fileList.value.map(file => file.objectUrl);  // 提取所有图片的 url
  // console.log(imgUrls);
  await axios.post("http://localhost:3000/yg/addHome", {
    name: text.value,
    address: address.value,
    price: price.value,
    desc: desc.value,
    houseType: houseType.value,
    img: imgUrls,
    u_id: id
  }).then(res => {
    if (res.data.code == 200) {
      text.value = ''
      address.value = ''
      price.value = ''
      desc.value = ''
      houseType.value = ''
      fileList.value = []
      ElMessage({
        message: '发布成功',
        type: 'success',
      })
    } else {
      ElMessage({
        message: '发布失败',
        type: 'error',
      })
    }
  })
}
</script>

<style scoped lang="scss">
* {
  padding: 0;
  margin: 0;
}

.lx_addhome {
  width: 100vw;
  height: 100vh;
  background: #f4f6f9;
}

p {
  border-bottom: 1px solid #ccc;
}

.add {
  width: 100%;
  height: 50px;

  .btn {
    width: 90%;
    height: 40px;
    background: #21b97a;
    color: #fff;
    border-radius: 10px;
    margin: 5px auto;
    margin-left: 18px;
    border: none;
  }
}
</style>
